<template>
  <el-dialog title="添加门店" :visible.sync="dialogAddVisible" :before-close="cancelDialog" >
    <el-form class="form" ref="shopAdd" :model="form" :rules="formRules">
      <el-form-item label="门店名称: " prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="门店简介: " prop="introduction">
        <el-input v-model="form.introduction"></el-input>
      </el-form-item>
      <el-form-item label="人均消费: " prop="pricePerMan">
        <el-input v-model.number="form.pricePerMan" type="number"></el-input>
      </el-form-item>
      <!--<el-form-item label="地址: " prop="address">-->
        <!--<el-input v-model="form.address">-->
          <!--<el-button slot="append" icon="el-icon-position" @click="findPosition"></el-button>-->
        <!--</el-input>-->
      <!--</el-form-item>-->
      <el-form-item label="品类: " prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择" :filterable="true">
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商户: " prop="sellerId">
        <el-select v-model="form.sellerId" placeholder="请选择" :filterable="true">
          <el-option
            v-for="item in sellerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签: " prop="tags">
        <el-input v-model="form.tags"></el-input>
      </el-form-item>
      <el-dialog :visible.sync="dialogMapVisible" :append-to-body="true">
        <b-map
               :formParent="form"
               :dialogMapVisible="dialogMapVisible"
               @update:formParent="updateAddress"
               @update:dialogMapVisible="dialogMapVisibles">
        </b-map>
      </el-dialog>
      <el-form-item label="地址: " prop="address">
        <el-input v-model="form.address" disabled>
          <el-button slot="append" icon="el-icon-position" @click="showMap"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="经度: " prop="latitude">
        <el-input v-model="form.latitude" disabled></el-input>
      </el-form-item>
      <el-form-item label="维度: " prop="longitude">
        <el-input v-model="form.longitude" disabled></el-input>
      </el-form-item>
      <el-form-item label="营业开始时间: " prop="startTime">
        <el-time-picker
          v-model="form.startTime"
          value-format="HH:mm:ss"
          :picker-options="{
          selectableRange: '00:00:00 - 23:59:59'}"
          placeholder="请选择营业开始时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="营业结束时间: " prop="endTime">
        <el-time-picker
          v-model="form.endTime"
          value-format="HH:mm:ss"
          :picker-options="{
          selectableRange: '00:00:00 - 23:59:59'}"
          placeholder="请选择营业结束时间">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="门店头像: ">
          <br>
          <el-upload
            ref="upload"
            action="http://localhost:8081/shop/save"
            name="img"
            :class="{hide:hideUpload}"
            :headers="headers"
            list-type="picture-card"
            :auto-upload=false
            :data="form"
            :limit=limitCount
            :on-success="handleSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleChange">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="imgSaveRequest">确 定</el-button>
      <el-button @click="cancelDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
    import {save} from '@/api/seller'
    import {getToken} from "@/utils/auth";
    import BMap from "@/views/BMap/index";
    export default {
      name: "ShopAddDialog",
      //父组件 传 过来的 值
      props: {
        dialogAddVisible: {
          type: Boolean,
          default: false
        },
        dialogInfo: {
          type: Object,
          default: {}
        },
        categoryOptions:{
          type:Array,
          default:{}
        },
        sellerOptions:{
          type:Array,
          default:{}
        },
      },
      watch: {
        //监听 弹窗显示， 可以用来写 请求接口
        dialogAddVisible: function(newVal, oldVal) {
          if (newVal) {
            console.log(newVal);
          }
        }
      },
      components: {
        BMap,
      },
      data() {
        return {
          dialogImageUrl: '',
          headers:{Authorization: getToken()},
          dialogVisible: false,
          dialogMapVisible: false,
          hideUpload: false,
          limitCount: 1,
          form:{
            name:'',
            introduction:'',
            pricePerMan:'',
            address:"",
            latitude:"",
            longitude:"",
            categoryId:'',
            tags:'',
            startTime:'07:00:00',
            endTime:'23:00:00',
            sellerId:'',
          },
          formRules: {
            name: [{ required: true, message: '请输入门店名称',trigger: 'blur' }],
            pricePerMan:[
              { required: true, type: 'number', min: 0,message: '请输入人均消费价格（最低消费0元）',trigger: 'blur' }
            ],
            address:[{ required: true, message: '请输入门店地址',trigger: 'blur' }],
            latitude:[{ required: true, message: '经度不能为空',trigger: 'blur' }],
            longitude:[{ required: true, message: '维度不能为空',trigger: 'blur' }],
            categoryId:[{ required: true, message: '请选择品类',trigger: 'blur' }],
            tags:[{ required: true, message: '请输入标签',trigger: 'blur' }],
            startTime:[{ required: true, message: '请选择门店营业开始时间',trigger: 'blur' }],
            endTime:[{ required: true, message: '请选择门店营业结束时间',trigger: 'blur' }],
            sellerId:[{ required: true, message: '请选择商家',trigger: 'blur' }],
          },
        };
      },
      computed: {
        // 这里定义上传文件时携带的参数，即表单数据
        upData: function() {
          return this.form
        },
      },
      created() {},
      mounted() {},
      methods: {
        //修改父组件传过来的值
        cancelDialog() {
          this.$emit("update:dialogAddVisible", false);
        },
        //同步子组件的值
        dialogMapVisibles(v){
          this.dialogMapVisible=v;
        },
        updateAddress(v){
          this.form = v
        },
        saveRequest(){
          save(this.form).then((response) => {
            if(response.data.code===200){
              this.$message({
                message: '保存成功',
                type: 'success'
              });
              this.$emit("update:dialogAddVisible", false);
              this.$emit('search');
            }else{
              this.$message.error(response.data.msg);
            }
          }).catch((response) => {
            console.log(response);
          });
          this.$parent.search();
        },
        imgSaveRequest(){
          this.$refs.shopAdd.validate((valid) => {
            if(valid){
              if (!this.hideUpload){
                this.$message.error('门店头像不能为空');
              }else{
                this.$refs.upload.submit();
              }
            }
          })
        },
        handleRemove(file, fileList) {
          this.hideUpload = fileList.length >= this.limitCount;
        },
        handleChange(file, fileList){
          this.hideUpload = fileList.length >= this.limitCount;
        },
        handlePictureCardPreview(file) {
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;
        },
        handleSuccess(response, file, fileList){
          if(response.code===200){
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            this.form.name='';
            this.form.introduction='';
            this.$emit("update:dialogAddVisible", false);
            this.$emit('search');
            this.$refs.upload.clearFiles();
          }else{
            this.$message.error(response.msg);
          }
        },
        handleError(err, file, fileList){
          this.$message({
            message: err,
            type: 'success'
          });
        },
        beforeAvatarUpload(file) {
          let check =true;
          this.$refs.shopAdd.validate((valid) => {
            check =valid;
          });
          if (!check) {
            return Promise;
          }
          const isJPG = file.type === 'image/jpeg';
          const isPNG = file.type === 'image/png';
          const isWEBP = file.type === 'image/webp';
          const isLt2M = file.size / 1024 / 1024 < 5;
          if (!isJPG&&!isPNG&&!isWEBP) {
            this.$message.error('上传图片只能是 JPG, PNG,WEBP 格式!');
          }
          if (!isLt2M) {
            this.$message.error('上传图片大小不能超过 5MB!');
          }
          return  (isJPG||isPNG||isWEBP) && isLt2M;
        },
        showMap(){
          this.dialogMapVisible =true;
        },
        findPosition(){
          this.$jsonp('http://api.map.baidu.com/geocoding/v3/', {
            address: this.form.address,
            output: 'json',
            ak: 'Iavfm6ydXMsSi7xPMIDlsSSGfSGRZdkW'
          }).then(json => {
            // 得到我们想要的内容
            console.log(json)
          }).catch(err => {
            console.log(err)
          })

        }
      }
    };
</script>

<style lang="scss">
  .form{
    padding: 0 10px;
  }
  .dialog-footer{
    text-align: center;
  }
  .hide .el-upload--picture-card {
    display: none;
  }
  .el-form .el-select{
    width: 100%;
  }
</style>
